<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
	Class: Auth

	Author: 
		Lonnie Ezell
*/
class CI_JimAuth{
	
	/*
		Var: $errors
		An array of errors generated.
	*/
	public	$errors	= array();
	
	/*
		Var: $login_destination
		The url to redirect to on successful login.
	*/
	public	$login_destination = '/';
	
	/*
		Var: $logged_in
		Stores the logged in value after the first test to improve performance.
		
		Access:
			Private
	*/
	private $logged_in = null;
	
	/*
		Var: $ip_address
		Stores the ip_address of the current user for performance reasons.
		
		Access:
			Private
	*/
	private $ip_address;
	
	/*
		Var: $perms
		Stores permissions by role so we don't have to scour the database more than once.
		
		Access:
			Private
	*/
	private $perms = array();
	
	/*
		Var: $ci
		A pointer to the CodeIgniter instance.
		
		Access:
			Private
	*/
	private $ci;

    public function __construct() 
    {
        $this->ci =& get_instance();
        
        if (!class_exists('CI_Session'))
        {
            $this->ci->load->library('session');
        }
        /*$this->ip_address = $this->ci->input->ip_address();
        
        // We need the users language file for this to work
        // from other modules.
        $this->ci->lang->load('users/users');
        
        log_message('debug', 'Auth class initialized.');
                
        
                
        // Try to log the user in from session/cookie data
        $this->autologin();
        */
    }
    
    function hash_password($str = 'hash')
    {
        $md5 = substr(md5($str), 5, 30);
        return sha1($md5);
    }
    
    public function logout(){
        //$this->ci->session->unset_userdata('logged_in');
        $this->ci->session->sess_destroy();
    }
    
    public function login($username=null, $password=null, $remember=false) 
    {
        if (empty($username) || empty($password)){
            return false;
        }
    
        if (!class_exists('user_model')){
            $this->ci->load->model('user_model');
        }
    
        $user_login = $this->ci->user_model->getUserByName($username);

        if($user_login == false){
            $this->errors[] = 'User khong ton tai';
            return false;
        }
        
        // check if the account has been soft deleted.
        if ($user_login->status == 11){
            $this->errors[] = 'User da bi xoa';
            return false;
        }
        
        /*if (!function_exists('do_hash')){
            $this->ci->load->helper('security');
        }*/
        
        $hash_password = $this->hash_password($password.$user_login->salt);

        if($hash_password == $user_login->password_hash){
            $fullname = $user_login->full_name;
            //$fullname = $user_login->first_name.' '.$user_login->last_name;
            $this->setup_session($user_login->id, $user_login->username, $user_login->password_hash, $user_login->email, $user_login->role_id, $remember, $fullname);
            return true;
        }
        
        return false;
    }
    
    public function setup_session($user_id=0, $username='', $password_hash=null, $email='', $role_id=0, $remember=false, $fullname='') 
    {

        if (empty($user_id) || (empty($email) && empty($username)))
        {
            return false;
        }
        
        $data = array(
            'user_id'        => $user_id,
            'user_name'=> $username,
            'user_fullname' => $fullname,
            'user_token'    => 'xxxxxxxx',//do_hash($user_id . $password_hash),
            'user_time'        => time(),
            'user_role'        => $role_id,
            'logged_in'        => true,
        );
        
        $this->ci->session->set_userdata($data);
        
        // Should we remember the user?
        /*if ($remember === true)
        {
            return $this->create_autologin($user_id, $old_token);
        }*/
        
        return true;
    }
    
    /*
     * Method: user_id()
     * Retrieves the user_id from the current session.
     * Return: The user's id.
    */
    public function user_id() {
        return (int) $this->ci->session->userdata('user_id');
    }
    public function role_id() 
    {
        return (int) $this->ci->session->userdata('user_role');
    }
    public function checkUserLogin(){
        if($this->ci->session->userdata('logged_in') === true){
            return true;
        }
        return false;
    }
    
    public function username()
    {        
        // We have to grab the user from the db and return his username. 
        if (!class_exists('user_model')){
            $this->ci->load->model('user_model');
        }
        $user_id = (int) $this->ci->session->userdata('user_id');
        $user_login = $this->ci->user_model->getUserById($user_id);
        return $user_login->username;    
    }
    
    public function has_permission($permission = null, $role_id=null)
    {
        if (!class_exists('user_model')){
            $this->ci->load->model('user_model');
        }
        if (empty($permission)){
            return false;
        }
        if (empty($role_id)){
            $role_id = $this->role_id();
        }
        $permissions = $this->ci->user_model->load_permissionsByRoleId($role_id);
        if( in_array($permission, $permissions) ){
            return true;
        }
        return false;
    }
    
}

if (!function_exists('has_permission')){
    function has_permission($permission=null, $role_id=null){
        $ci =& get_instance();
        if (class_exists('CI_JimAuth')){
            return $ci->jimauth->has_permission($permission, $role_id); 
        }
        return false;
    }
}